package com.supplychainapi.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.joindata.inf.common.basic.exceptions.ServiceException;
import com.supplychainapi.common.RestResponse;
import com.supplychainapi.common.exception.ExceptionManager;
import com.supplychainapi.dao.prod.TbauthorityMapper;
import com.supplychainapi.dao.prod.TbauthoritydtlMapper;
import com.supplychainapi.dao.prod.TbroleMapper;
import com.supplychainapi.domain.*;
import com.supplychainapi.model.ScmTbseqno;
import com.supplychainapi.model.Tbauthority;
import com.supplychainapi.model.Tbauthoritydtl;
import com.supplychainapi.model.Tbrole;
import com.supplychainapi.param.ColTitle;
import com.supplychainapi.service.RoleService;
import com.supplychainapi.service.TbSeqNoService;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class RoleServiceImpl implements RoleService {

    private static Logger logger = LogManager.getLogger(RoleServiceImpl.class);
    @Autowired
    TbSeqNoService tbSeqNoService;
    @Autowired
    TbauthorityMapper tbauthorityMapper;
    @Autowired
    TbauthoritydtlMapper tbauthoritydtlMapper;
    @Autowired
    TbroleMapper tbroleMapper;
    private LoginCache loginCache;
    // ------------- ListMap结束        [end] --------------
    /**
     * 解析requestRoleAddEntity的ListMap [start] saveRoleAuth方法使用
     */
    private List<Tbauthority> tbauthorityList = new ArrayList<Tbauthority>();
    private List<Tbauthoritydtl> tbauthoritydtlList = new ArrayList<Tbauthoritydtl>();
    private Map<String, Tbauthority> authMap = new HashMap<String, Tbauthority>();
    private Map<String, Tbauthoritydtl> authMapDtl = new HashMap<String, Tbauthoritydtl>();


    @Override
    public PageInfo list(LoginCache loginCache, String fsRoleName, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy("fsCreateTime DESC");
        List<RoleEntity> list = tbroleMapper.getList(loginCache.getFsShopGUID(), fsRoleName);
        list.forEach((RoleEntity role) -> {
            if (role.getFiStatus() == 1) {
                role.setFiStatusName("正常");
            }
        });
        return new PageInfo(list);
    }

    @Override
    public List<ColTitle> getSchema() {
        List<ColTitle> list = new ArrayList<ColTitle>();
        list.add(new ColTitle("fsRoleName", "角色名称", "left", 200));
        list.add(new ColTitle("fiStatusName", "状态", "left", 100));
        list.add(new ColTitle("fsUpdateTime", "建立日期", "center", 100));
        list.add(new ColTitle("__EDIT__", "操作", "center", 150, "fsRoleId"));
        return list;
    }

    /**
     * 获取角色权限
     *
     * @param loginCache
     * @param role
     * @return
     */
    @Override
    public RoleAuthEntity getRoleAuth(LoginCache loginCache, Tbrole role) {
        RoleAuthEntity roleAuthEntity = new RoleAuthEntity();

        Map<String, Integer> authA = new HashMap<String, Integer>();
        Map<String, Integer> authC = new HashMap<String, Integer>();
        Map<String, Integer> authD = new HashMap<String, Integer>();

        if (role != null) {

            // 根据role获取auth信息
            List<HashMap<String, String>> authList = tbroleMapper.findUserAuthList(loginCache.getFsShopGUID(), role.getFsRoleId());

            if (authList != null && authList.size() > 0) {
                for (Map<String, String> authOne : authList) {
                    String fiShopKind = String.valueOf(authOne.get("fiShopKind"));
                    String fsProjId = authOne.get("fsProjId");
                    String fsProgId = authOne.get("fsProgId");
                    String fsProgDtlId = authOne.get("fsProgDtlId");
                    String pjPgKey = fsProjId + fsProgId;
                    String pjPgPgdKey = pjPgKey + fsProgDtlId;

                    if ("0".equals(fiShopKind)) {
                        setAuthCount(authA, pjPgKey, pjPgPgdKey, fsProjId);
                    }

                    if ("3".equals(fiShopKind)) {
                        setAuthCount(authC, pjPgKey, pjPgPgdKey, fsProjId);
                    }

                    if ("7".equals(fiShopKind)) {
                        setAuthCount(authD, pjPgKey, pjPgPgdKey, fsProjId);
                    }
                }
            }

            RoleInfoEntity roleInfoEntity = new RoleInfoEntity();
            roleInfoEntity.setFsRoleId(role.getFsRoleId());
            roleInfoEntity.setFsRoleName(role.getFsRoleName());
            roleAuthEntity.setRoleInfo(roleInfoEntity);
        }

        roleAuthEntity.setRoleInfo(null);

        String fsShopType = loginCache.getFsShopType();

        List<HashMap<String, String>> progList = tbroleMapper.findProgList();
        List<HashMap<String, String>> progDtlList = tbroleMapper.findProgDtlList();
        if ("A".equals(fsShopType)) {
            roleAuthEntity.setAuthA(getRoleProj("A", progList, progDtlList, authA));
            roleAuthEntity.setAuthC(getRoleProj("C", progList, progDtlList, authC));
            roleAuthEntity.setAuthD(getRoleProj("D", progList, progDtlList, authD));
        } else if ("C".equals(fsShopType)) {
            roleAuthEntity.setAuthC(getRoleProj("C", progList, progDtlList, authC));
            roleAuthEntity.setAuthD(getRoleProj("D", progList, progDtlList, authD));
        } else if ("D".equals(fsShopType)) {
            roleAuthEntity.setAuthD(getRoleProj("D", progList, progDtlList, authD));
        }
        roleAuthEntity.setShopType(fsShopType);
        return roleAuthEntity;
    }

    /**
     * 获取角色权限
     *
     * @param loginCache
     * @param roleId
     * @return
     */
    @Override
    public RestResponse<RoleAuthEntity> getRoleAuthResponse(LoginCache loginCache, String roleId) {
        if (StringUtils.isBlank(roleId)) {
            throw ExceptionManager.fail("角色id必传");
        }
        Tbrole role = tbroleMapper.findNormalRole(loginCache.getFsShopGUID(), roleId);
        if (role == null) {
            throw ExceptionManager.fail("角色不存在");
        }
        return RestResponse.success(getRoleAuth(loginCache, role));
    }

    /**
     * 删除角色和权限
     *
     * @param loginCache
     * @param fsRoleId
     * @return
     */
    @Override
    @Transactional
    public RestResponse delete(LoginCache loginCache, String fsRoleId) {
        String fsShopGUID = loginCache.getFsShopGUID();
        Tbrole filter = new Tbrole();
        filter.setFsShopGUID(loginCache.getFsShopGUID());
        filter.setFsRoleId(fsRoleId);
        Tbrole tbrole = tbroleMapper.selectOne(filter);

        if (tbrole == null) {
            throw ExceptionManager.fail("角色不存在，无法删除");
        }

        if (tbrole.getFiStatus() == 13) {
            return RestResponse.success("删除成功");
        }

        Integer count = tbroleMapper.findUserRoleCountByRoleId(fsShopGUID, fsRoleId);
        // 判断权限是否被用户取用
        if (count != null && count > 0) {
            throw ExceptionManager.fail("无法删除，该角色已经被用户关联");
        }

        try {
            // 删除角色id
            tbroleMapper.deleteByRoleId(fsShopGUID, fsRoleId);

            // 删除功能权限
            tbauthorityMapper.deleteByRoleId(fsShopGUID, fsRoleId);

            // 删除功能权限明细
            tbauthoritydtlMapper.deleteByRoleId(fsShopGUID, fsRoleId);

        } catch (Exception e) {
            e.printStackTrace();
            logger.info("fsShopGUID:{}, fsRoleId:{}, 删除失败:{}", fsShopGUID, fsRoleId, e.getMessage());
            throw ExceptionManager.fail("删除失败");
        }

        return RestResponse.success("删除成功");
    }

    /**
     * 编辑角色和权限
     *
     * @param loginCache
     * @param requestRoleAddEntity
     * @return
     */
    @Override
    @Transactional
    public RestResponse edit(LoginCache loginCache, RequestRoleAddEntity requestRoleAddEntity) {
        String fsShopGUID = loginCache.getFsShopGUID();
        String fsRoleId = requestRoleAddEntity.getFsRoleId();

        // 判断传过来的roleId是否存在
        Tbrole tbrole = tbroleMapper.findNoDeleteByRoleId(fsShopGUID, fsRoleId);

        if (tbrole == null) {
            throw ExceptionManager.fail("该角色不存在或已被删除");
        }

        saveRoleAuth(loginCache, tbrole, requestRoleAddEntity);

        return RestResponse.success("编辑成功");
    }

    /**
     * 新增角色和权限
     *
     * @param loginCache
     * @param requestRoleAddEntity
     * @return
     */
    @Override
    @Transactional
    public RestResponse add(LoginCache loginCache, RequestRoleAddEntity requestRoleAddEntity) {
        String fsShopGUID = loginCache.getFsShopGUID();
        String fsRoleName = requestRoleAddEntity.getFsRoleName();

        Tbrole role = tbroleMapper.findNoDeleteByRoleName(fsShopGUID, fsRoleName);
        if (role != null) {
            throw ExceptionManager.fail("角色已经存在");
        }

        ScmTbseqno seqno = new ScmTbseqno();
        seqno.setFsCls("TbRole");
        seqno.setFsShopGUID(fsShopGUID);
        String fsRoleId = "";
        try {
            fsRoleId = tbSeqNoService.selectSeqNo(seqno);
        } catch (ServiceException e) {
            e.printStackTrace();
            throw ExceptionManager.fail("新增角色失败");
        }

        String fsUserId = loginCache.getFsUserId();
        String fsUserName = loginCache.getFsUserName();
        Date now = new Date();

        Tbrole tbrole = new Tbrole();
        tbrole.setFsRoleId(fsRoleId);
        tbrole.setFsRoleName(fsRoleName);
        tbrole.setFsShopGUID(fsShopGUID);
        tbrole.setFiStatus((short) 1);
        tbrole.setFiDataKind((short) 2);
        tbrole.setFsCreateTime(now);
        tbrole.setFsCreateUserId(fsUserId);
        tbrole.setFsCreateUserName(fsUserName);
        tbrole.setFsUpdateTime(now);
        tbrole.setFsUpdateUserId(fsUserId);
        tbrole.setFsUpdateUserName(fsUserName);
        tbrole.setFsDataSource("comp");

        if (loginCache.getFsShopType().equals("D")) {
            tbrole.setFsDataSource("shop");
        }

        try {
            save(tbrole);
            saveRoleAuth(loginCache, tbrole, requestRoleAddEntity);
        } catch (Exception e) {
            logger.info("保存角色数据失败, 角色信息{}, 错误信息:{}", JSONObject.toJSONString(tbrole), e.getMessage());
            throw ExceptionManager.fail("新增角色失败");
        }

        return RestResponse.success("新增成功");
    }

    /**
     * 保存角色相关权限
     *
     * @param loginCache
     * @param tbrole
     * @param requestRoleAddEntity
     * @return
     */
    private void saveRoleAuth(LoginCache loginCache, Tbrole tbrole, RequestRoleAddEntity requestRoleAddEntity) {
        Date now = new Date();
        String fsShopGUID = loginCache.getFsShopGUID();
        String fsUserId = loginCache.getFsUserId();
        String fsUserName = loginCache.getFsUserName();
        String fsRoleId = tbrole.getFsRoleId();

//        List<Tbauthority> tbauthorityList = new ArrayList<Tbauthority>();
//        List<Tbauthoritydtl> tbauthoritydtlList = new ArrayList<Tbauthoritydtl>();
//
//
//        Map<String, Tbauthority> authMap = new HashMap<String, Tbauthority>();
//        Map<String, Tbauthoritydtl> authMapDtl = new HashMap<String, Tbauthoritydtl>();


        String fsShopType = loginCache.getFsShopType();

        if (authMap.size() == 0) {
            boolean booleanA = (requestRoleAddEntity.getAuthA() != null && requestRoleAddEntity.getAuthA().size() > 0);
            boolean booleanC = (requestRoleAddEntity.getAuthC() != null && requestRoleAddEntity.getAuthC().size() > 0);
            boolean booleanD = (requestRoleAddEntity.getAuthD() != null && requestRoleAddEntity.getAuthD().size() > 0);


            String finalFsRoleId = tbrole.getFsRoleId();
            if (fsShopType.equals("A") && booleanA) {
                requestRoleAddEntity.getAuthA().forEach(auth -> {
                    setAuthorityList(loginCache, auth, now, (short) 0, tbauthorityList, authMap, finalFsRoleId);
                    setAuthorityDtlList(loginCache, auth, now, (short) 0, tbauthoritydtlList, authMapDtl, finalFsRoleId);
                });
            }

            if ((fsShopType.equals("C") || fsShopType.equals("A")) && booleanC) {
                requestRoleAddEntity.getAuthC().forEach(auth -> {
                    setAuthorityList(loginCache, auth, now, (short) 3, tbauthorityList, authMap, finalFsRoleId);
                    setAuthorityDtlList(loginCache, auth, now, (short) 3, tbauthoritydtlList, authMapDtl, finalFsRoleId);
                });
            }

            if ((fsShopType.equals("D") || fsShopType.equals("C") || fsShopType.equals("A")) && booleanD) {
                requestRoleAddEntity.getAuthD().forEach(auth -> {
                    setAuthorityList(loginCache, auth, now, (short) 7, tbauthorityList, authMap, finalFsRoleId);
                    setAuthorityDtlList(loginCache, auth, now, (short) 7, tbauthoritydtlList, authMapDtl, finalFsRoleId);
                });
            }
        }

        // insert数据列表
        List<Tbauthority> insertData = new ArrayList<Tbauthority>();
        List<Tbauthoritydtl> insertDataDtl = new ArrayList<Tbauthoritydtl>();

        // update数据列表
        List<Tbauthority> updateData = new ArrayList<Tbauthority>();
        List<Tbauthoritydtl> updateDataDtl = new ArrayList<Tbauthoritydtl>();

        // 当前权限列表
        List<Tbauthority> list = tbauthorityMapper.findListByRoleId(fsShopGUID, fsRoleId);
        try {
            if (list.size() == 0) {
                tbauthorityMapper.batchInsert(tbauthorityList);
                tbauthoritydtlMapper.batchInsert(tbauthoritydtlList);
            } else {
                // 当前权限列表明细
                List<Tbauthoritydtl> listDtl = tbauthoritydtlMapper.findListByRoleId(fsShopGUID, fsRoleId);
                // 对比权限功能点是否存在，找出赠删改的数据列表
                // 循环当前已有的权限列表
                list.forEach(auth -> {
                    String key = auth.getFsProjId() + auth.getFsProgId() + String.valueOf(auth.getFiShopKind());
                    // 新增的列表中存在老数据
                    if (authMap.containsKey(key)) {
                        updateData.add(authMap.get(key));
                    } else {
                        if (auth.getFiStatus() != 13) {
                            auth.setFiStatus((short) 13);
                            auth.setFsUpdateTime(now);
                            auth.setFsUpdateUserId(fsUserId);
                            auth.setFsUpdateUserName(fsUserName);
                            updateData.add(auth);
                        }

                    }
                    authMap.remove(key);
                });

                if (authMap.size() > 0) {
                    authMap.forEach((s, auth) -> {
                        insertData.add(auth);
                    });
                }

                listDtl.forEach(authDtl -> {
                    String key = authDtl.getFsProjId() + authDtl.getFsProgId() + authDtl.getFsProgDtlId() + String.valueOf(authDtl.getFiShopKind());
                    // 新增的列表
                    if (authMapDtl.containsKey(key)) {
                        updateDataDtl.add(authMapDtl.get(key));
                    } else {
                        if (authDtl.getFiStatus() != 13) {
                            authDtl.setFiStatus((short) 13);
                            authDtl.setFiUsable((short) 0);
                            authDtl.setFsUpdateTime(now);
                            updateDataDtl.add(authDtl);
                        }
                    }
                    authMapDtl.remove(key);
                });

                if (authMapDtl.size() > 0) {
                    authMapDtl.forEach((s, authDtl) -> {
                        insertDataDtl.add(authDtl);
                    });
                }
                // 批量新增功能权限
                if (insertData.size() > 0) {
                    tbauthorityMapper.batchInsert(insertData);
                }
                // 批量新增功能明细权限
                if (insertDataDtl.size() > 0) {
                    tbauthoritydtlMapper.batchInsert(insertDataDtl);
                }
                // 批量更新功能权限
                if (updateData.size() > 0) {
                    tbauthorityMapper.batchUpdate(updateData);
                }
                // 批量更新功能明细权限
                if (updateDataDtl.size() > 0) {
                    tbauthoritydtlMapper.batchUpdate(updateDataDtl);
                }
            }
        } catch (Exception e) {
            logger.info("角色权限处理失败,失败原因:{}", e.getMessage());
            throw ExceptionManager.fail("角色权限处理失败");
        }
    }

    /**
     * 设置功能权限数据
     *
     * @param loginCache
     * @param auth
     * @param now
     * @param fiShopKind
     * @param list
     * @param authMap
     * @param fsRoleId
     */
    private void setAuthorityList(LoginCache loginCache, RequestRoleAddAuthEntity auth, Date now, Short fiShopKind, List<Tbauthority> list, Map<String, Tbauthority> authMap, String fsRoleId) {
        Tbauthority data = new Tbauthority();
        data.setFsProjId(auth.getFsProjId());
        data.setFsProgId(auth.getFsProgId());
        data.setFiShopKind(fiShopKind);
        data.setFiStatus((short) 1);
        data.setFsCreateTime(now);
        data.setFsCreateUserId(loginCache.getFsUserId());
        data.setFsCreateUserName(loginCache.getFsUserName());
        data.setFsUpdateTime(now);
        data.setFsUpdateUserId(loginCache.getFsUserId());
        data.setFsUpdateUserName(loginCache.getFsUserName());
        data.setFsShopGUID(loginCache.getFsShopGUID());
        data.setFsRoleId(fsRoleId);
        list.add(data);
        String key = data.getFsProjId() + data.getFsProgId() + String.valueOf(fiShopKind);
        authMap.put(key, data);
    }

    /**
     * 设置功能权限明细数据
     *
     * @param loginCache
     * @param auth
     * @param now
     * @param fiShopKind
     * @param list
     * @param authDtlMap
     * @param fsRoleId
     */
    private void setAuthorityDtlList(LoginCache loginCache, RequestRoleAddAuthEntity auth, Date now, Short fiShopKind, List<Tbauthoritydtl> list, Map<String, Tbauthoritydtl> authDtlMap, String fsRoleId) {
        Tbauthoritydtl data = new Tbauthoritydtl();
        data.setFsRoleId(fsRoleId);
        data.setFsProjId(auth.getFsProjId());
        data.setFsProgId(auth.getFsProgId());
        data.setFsProgDtlId(auth.getFsProgDtlId());
        data.setFiStatus((short) 1);
        data.setFiUsable((short) 1);
        data.setFiShopKind(fiShopKind);
        data.setFsUpdateTime(now);
        data.setFsShopGUID(loginCache.getFsShopGUID());
        list.add(data);
        String key = data.getFsProjId() + data.getFsProgId() + data.getFsProgDtlId() + String.valueOf(fiShopKind);
        authDtlMap.put(key, data);
    }

    private void setAuthCount(Map<String, Integer> auth, String pjPgKey, String pjPgPgdKey, String fsProjId) {
        if (!auth.containsKey(pjPgKey)) {
            auth.put(pjPgKey, 1);
        } else {
            auth.put(pjPgKey, (auth.get(pjPgKey) + 1));
        }
        auth.put(pjPgPgdKey, 1);
//        if (!auth.containsKey(fsProjId)) {
//            auth.put(fsProjId, 1);
//        } else {
//            auth.put(fsProjId, (auth.get(fsProjId) + 1));
//        }
    }

    private List<RoleProjEntity> getRoleProj(String fsShopType, List<HashMap<String, String>> progList, List<HashMap<String, String>> progDtlList, Map<String, Integer> auth) {

        List<RoleProjEntity> roleProjList = new ArrayList<RoleProjEntity>();

        HashMap<String, List<RoleProgDtlEntity>> progDtlMap = new HashMap<String, List<RoleProgDtlEntity>>();
        Map<String, Integer> pIndexMap = new HashMap<String, Integer>();
        for (HashMap<String, String> progDtl : progDtlList) {
            String fsProgId = progDtl.get("fsProgId");
            String fsProgDtlId = progDtl.get("fsProgDtlId");
            String fsProgDtlName = progDtl.get("fsProgDtlName");

            List<RoleProgDtlEntity> pprogDtlList = new ArrayList<RoleProgDtlEntity>();
            if (!progDtlMap.containsKey(fsProgId)) {
                progDtlMap.put(fsProgId, pprogDtlList);
            } else {
                pprogDtlList = progDtlMap.get(fsProgId);
            }

            // 记录progDtl在prog中的索引的位置
            String pgPgdKey = fsProgId + fsProgDtlId;
            if (!pIndexMap.containsKey(fsProgId)) {
                pIndexMap.put(pgPgdKey, 0);
            } else {
                pIndexMap.put(pgPgdKey, (pIndexMap.get(pgPgdKey) + 1));
            }

            RoleProgDtlEntity roleProgDtlEntity = new RoleProgDtlEntity();
            roleProgDtlEntity.setFsProgDtlId(fsProgDtlId);
            roleProgDtlEntity.setFsProgDtlName(fsProgDtlName);
            roleProgDtlEntity.setFsProgId(fsProgId);

            pprogDtlList.add(roleProgDtlEntity);
            progDtlMap.put(fsProgId, pprogDtlList);
        }

        // 项目索引值
        Integer projIdx = 0;

        for (HashMap<String, String> prog : progList) {
            // 项目id
            String fsProjId = prog.get("fsProjId");
            // 项目名称
            String fsProjName = prog.get("fsProjName");
            // 功能id
            String fsProgId = prog.get("fsProgId");
            // 功能名称
            String fsProgName = prog.get("fsProgName");

            String pjPgKey = fsProjId + fsProgId;


            RoleProjEntity roleProj = new RoleProjEntity();
            RoleProgEntity roleProg = new RoleProgEntity();
            // 针对账号类型遍历数据
            if (prog.get("fsProgLvl").contains(fsShopType)) {

                if (!pIndexMap.containsKey(fsProjId)) {
                    roleProj.setFsProjId(fsProjId);
                    roleProj.setFsProjName(fsProjName);
                    roleProj.setTbprog(new ArrayList<RoleProgEntity>());
                    roleProjList.add(roleProj);
                    pIndexMap.put(fsProjId, projIdx);
                    projIdx++;
                }

                // progDtl填充projID
                for (RoleProgDtlEntity roleProgDtlEntity : progDtlMap.get(fsProgId)) {
                    roleProgDtlEntity.setFsProjId(fsProjId);
                }

//                String progDtlCountlKey = fsProjId + "count";
//                if (!pIndexMap.containsKey(progDtlCountlKey)) {
//                    pIndexMap.put(progDtlCountlKey, progDtlMap.get(fsProgId).size());
//                } else {
//                    pIndexMap.put(progDtlCountlKey, (pIndexMap.get(progDtlCountlKey) + progDtlMap.get(fsProgId).size()));
//                }

                roleProg.setFsProgId(fsProgId);
                roleProg.setFsProgName(fsProgName);
                // 计算该prog下有多少个progDtl
//                roleProg.setProgCount(progDtlMap.get(fsProgId).size());
                // 判断prog是否应该被选中, 对比 选中的明细个数 和 当前明细个数
                if (auth.get(pjPgKey) != null && auth.get(pjPgKey) == progDtlMap.get(fsProgId).size()) {
                    roleProg.setChecked(1);
                }

                // 判断progdtl是否被选中，并设置项目id
                progDtlMap.get(fsProgId).forEach(roleProgDtlEntity -> {
                    roleProgDtlEntity.setFsProjId(fsProjId);
                    String key = fsProjId + roleProgDtlEntity.getFsProgId() + roleProgDtlEntity.getFsProgDtlId();
                    roleProgDtlEntity.setChecked(0);
                    if (auth.containsKey(key)) {
                        roleProgDtlEntity.setChecked(1);
                    }
                });

                roleProg.setTbprogdtl(progDtlMap.get(fsProgId));
                roleProjList.get(pIndexMap.get(fsProjId)).getTbprog().add(roleProg);

                // 记录prog在proj中的索引的位置
                if (!pIndexMap.containsKey(pjPgKey)) {
                    pIndexMap.put(pjPgKey, 0);
                } else {
                    pIndexMap.put(pjPgKey, (pIndexMap.get(pjPgKey) + 1));
                }
            }
        }
//        roleProjList.forEach((RoleProjEntity roleProjEntity) -> {
//            Integer count = pIndexMap.get(roleProjEntity.getFsProjId() + "count");
//            // 判断proj是否被选中
//            if (auth.get(roleProjEntity.getFsProjId()) != null && count == auth.get(roleProjEntity.getFsProjId())) {
//                roleProjEntity.setChecked(1);
//            }
//            roleProjEntity.setProjCount(count);
//        });

        return roleProjList;
    }

//    /**
//     * 保存下发的角色权限数据
//     */
//    private void saveDown(LoginCache loginCache, RequestRoleAddEntity requestRoleAddEntity) {
//        // 查看当前用户类型, 当前用户类型是企业账户,操作角色权限可能被下发
//        if (loginCache.getFsShopType().equals("C")) {
//            this.loginCache = loginCache;
//            // 查询当前角色是否被下发
//
//
//            saveRoleAuth(this.loginCache, tbrole, requestRoleAddEntity);
//        }
//
//    }

    /**
     * 保存下发的角色权限数据
     */
//    private void saveDown(LoginCache loginCache, RequestRoleAddEntity requestRoleAddEntity) {
//        // 查看当前用户类型, 当前用户类型是企业账户,操作角色权限可能被下发
//        if (loginCache.getFsShopType().equals("C")) {
//            this.loginCache = loginCache;
//            // 查询当前角色是否被下发
//
//
//            saveRoleAuth(this.loginCache, tbrole, requestRoleAddEntity);
//        }
//
//    }

    /**
     * 保存下发的角色权限数据
     */
    private void saveDown(LoginCache loginCache, RequestRoleAddEntity requestRoleAddEntity) {
        // 查看当前用户类型, 当前用户类型是企业账户,操作角色权限可能被下发
        if (loginCache.getFsShopType().equals("C")) {
            this.loginCache = loginCache;
            // 查询当前角色是否被下发
            List<HashMap<String, String>> list = tbroleMapper.findDownRoleList(loginCache.getFsShopGUID(), requestRoleAddEntity.getFsRoleId());

            list.forEach(role -> {
                this.loginCache.setFsShopGUID(role.get("fsShopGUID"));
                Tbrole tbrole = new Tbrole();
                tbrole.setFsRoleId(role.get("fsRoleId"));
                saveRoleAuth(this.loginCache, tbrole, requestRoleAddEntity);
            });
        }
    }

    /**
     * 保存角色数据存在则更新不存在则删除
     *
     * @param tbrole
     */
    private void save(Tbrole tbrole) {
        // 如果发现同名称已经处于删除状态的角色
        Tbrole role = tbroleMapper.findDeleteByRoleName(tbrole.getFsShopGUID(), tbrole.getFsRoleName());
        if (role != null) {
            // 将删除的角色直接还原到新增的角色上
            tbrole.setFsRoleId(role.getFsRoleId());
            tbroleMapper.updateRole(tbrole);
        } else {
            // 不存在则直接新增
            tbroleMapper.insert(tbrole);
        }
    }
}
